package guoanmaker.personal.business.scheduled;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import guoanmaker.personal.business.dao.PersonalOrderFormDao;
import guoanmaker.personal.business.model.MessageType;
import guoanmaker.personal.business.model.OperatorCoupons;
import guoanmaker.personal.business.model.PersonalUserCoupon;
import guoanmaker.personal.business.model.ProvideOrderForm;
import guoanmaker.personal.business.modelnobind.JsonAnalyze;
import guoanmaker.personal.business.repository.MessageTypeRepository;
import guoanmaker.personal.business.repository.OperatorCouponsRepository;
import guoanmaker.personal.business.repository.PersonalOrderFormRepository;
import guoanmaker.personal.business.repository.PersonalUserCouponRepository;
import guoanmaker.personal.business.service.PersonalOrderFormService;
import guoanmaker.personal.helper.common.abstractobj.ApiController;
import guoanmaker.personal.helper.common.util.SystemHelper;
import guoanmaker.personal.helper.jpa.Criteria;
import guoanmaker.personal.helper.jpa.Restrictions;


@Component
public class OrderScheduled {
	@Resource
	private PersonalOrderFormDao personalOrderFormDao;
	
	@Resource
	private PersonalOrderFormRepository personalOrderFormRepository;
	
	@Resource
	private PersonalOrderFormService personalOrderFormService;
	
	@Resource
	private PersonalUserCouponRepository personalUserCouponRepository;
	
	@Resource
	private OperatorCouponsRepository operatorCouponsRepository;
	
	@Resource
	private MessageTypeRepository messageTypeRepository;

	/**
	 * 
	* @Description: 轮循所有已发起支付的订单，循环查询支付结果 
	* @param @throws Exception
	* @author Yvonne_MGL 
	* @date 2017年8月21日 下午3:13:10     
	* @return void    
	* @throws 
	 */
	@Scheduled(fixedRate = 300000)
	@Transactional
	public void readDefrayState() throws Exception{
		
		List<ProvideOrderForm> list = personalOrderFormDao.getOrders();
		if(list!=null&&list.size()>0){
			for (int i = 0; i < list.size(); i++) {
				ProvideOrderForm orderForm=list.get(i);
				String url=ApiController.PAY_URL+"retrieve.php";
				String param="isJava=1&pingId="+orderForm.getDefrayNumber();
				String result=SystemHelper.httpGetHelper(url, param);
				if(result!=null&&result.equals("1")){
					if(orderForm.getCommodity().getType().equals("3")||orderForm.getPlaceOrderType().equals("3")){
						orderForm.setOrderStatus("6");
					}else{
						orderForm.setOrderStatus("2");
					}
					orderForm.setDefrayTime(new Date());
					orderForm.setIsRead("0");
					if(orderForm.getPaymentMethod()!=null&&(orderForm.getPaymentMethod().equals("wx_pub_qr")||orderForm.getPaymentMethod().equals("alipay_pc_direct")||
							orderForm.getPaymentMethod().equals("alipay")||orderForm.getPaymentMethod().equals("wx")||
							orderForm.getPaymentMethod().equals("wx_h5")||orderForm.getPaymentMethod().equals("wx_js")||orderForm.getPaymentMethod().equals("alipay_h5"))){
						int price=Integer.parseInt((orderForm.getRealPrice() * 100 + "").substring(0, (orderForm.getRealPrice() * 100 + "").indexOf(".")));
						
						if(orderForm.getPreferentialMoney()!=null&&orderForm.getPreferentialMoney()>0){
							price=price-Integer.parseInt((orderForm.getPreferentialMoney() * 100 + "").substring(0, (orderForm.getPreferentialMoney() * 100 + "").indexOf(".")));
							if(orderForm.getCouponid()!=null&&!orderForm.getCouponid().equals("")){
								PersonalUserCoupon puCoupon=personalUserCouponRepository.findOne(orderForm.getCouponid());
								puCoupon.setIsUsed("1");
								personalUserCouponRepository.save(puCoupon);
								OperatorCoupons oCoupons=puCoupon.getOperatorCoupon();
								oCoupons.setBeenused(oCoupons.getBeenused()+1);
								operatorCouponsRepository.save(oCoupons);
							}
						}
						
						Map map=JsonAnalyze.getJsonValues(orderForm.getCommodity().getProviderBusiness().getId());
						String totalBail=(String)map.get("totalBail");
						String bail_rate=(String)map.get("bail_rate");
						String commission_rate=(String)map.get("commission_rate");
						int sumBail=personalOrderFormDao.getSumBail(orderForm.getCommodity().getProviderBusiness().getId());
						
						if(orderForm.getPaymentMethod().equals("wx_pub_qr")||orderForm.getPaymentMethod().equals("wx")||orderForm.getPaymentMethod().equals("wx_h5")||orderForm.getPaymentMethod().equals("wx_js")){
							orderForm.setFee(new BigDecimal(orderForm.getRealPrice()*5.5/1000));
						}else if(orderForm.getPaymentMethod().equals("alipay_pc_direct")||orderForm.getPaymentMethod().equals("alipay")||orderForm.getPaymentMethod().equals("alipay_h5")){
							orderForm.setFee(new BigDecimal(orderForm.getRealPrice()*1/100));
						}
						//price=price-Integer.parseInt((orderForm.getFee().doubleValue() * 100 + "").substring(0, (orderForm.getFee().doubleValue() * 100 + "").indexOf(".")));
						if(totalBail!=null&&Integer.parseInt(totalBail)>sumBail){
							int rate=10;
							if(bail_rate!=null&&Integer.parseInt(bail_rate)>1&&Integer.parseInt(bail_rate)<100){
								rate=Integer.parseInt(bail_rate);
							}
							int bail=0;
							if(price*rate/100<(Integer.parseInt(totalBail)-sumBail)){
								bail=price*rate/100;
							}else{
								bail=Integer.parseInt(totalBail)-sumBail;
							}
							Double double1=(double) bail;
							orderForm.setBail(new BigDecimal(double1/100));
							
							//price=price-bail;
						}
						int c_rate=10;
						if(commission_rate!=null&&Integer.parseInt(commission_rate)>1&&Integer.parseInt(commission_rate)<100){
							c_rate=Integer.parseInt(commission_rate);
						}
						Double double2=(double) price*c_rate/100;
						orderForm.setCommission(new BigDecimal(double2/100));
						
					}
					personalOrderFormRepository.save(orderForm);
					MessageType messageType=new MessageType();
					messageType.setType(1);
					messageType.setSourceid(orderForm.getId());
					messageType.setIsread(0);
					messageType.setDecribestr("您有一笔【"+orderForm.getCommodity().getCommodityName()+"】订单待接单，需您处理。");
					messageType.setCreatedate(new Date());
					messageType.setBusinessid(orderForm.getCommodity().getProviderBusiness().getId());
					messageTypeRepository.save(messageType);
				}
			}
		}
	}
	
	/**
	 * 
	* @Description: 自动确认7天服务商已完成的订单
	* @param 
	* @author Yvonne_MGL 
	* @date 2017年8月24日 下午3:49:06     
	* @return void    
	* @throws 
	 */
	@Scheduled(fixedRate = 300000)
	public void confirmOrders(){
		Date date=SystemHelper.getLess7Days();
		Criteria<ProvideOrderForm> criteria = new Criteria<>();
		criteria.add(Restrictions.eq("orderStatus", "4",true));
		criteria.add(Restrictions.gte("applyforCompleteTime", date,true));
		List<ProvideOrderForm> list = personalOrderFormRepository.findAll(criteria);
		if(list!=null&&list.size()>0){
			for (int i = 0; i < list.size(); i++) {
				personalOrderFormService.confirmOrder(list.get(i).getId());
			}
		}
	}
}
